package com.atguigu.gmall.mq.reveiver;

import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 小兰
 * @Date: 2023/5/9 18:57
 */
@Component
@Slf4j
public class DelayMsgReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @RabbitListener(
            queues = {DelayedMqConfig.queue_delay_1}
    )
    public  void  processDeadLetter(String msg, Message message, Channel channel){
        try {
            if (StringUtils.isNotBlank(msg)){
                //控制同样一个消息只能被消费一次:增加幂等性处理机制
                String key = "mq:"+msg;
                Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, "", 110, TimeUnit.MINUTES);
                if (!aBoolean){
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                    return;
                }
                log.info("基于延迟插件监听到消息:{}", msg);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("监听延迟消息异常:{}", e);

        }

    }
}
